import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import './ShowMaterialRequest.css';

const ShowMaterialRequest = () => {
  const { materialRequestId } = useParams();
  const [materialRequest, setMaterialRequest] = useState(null);

  useEffect(() => {
    const fetchMaterialRequest = async () => {
      try {
        const response = await fetch(`/show/material_request/${materialRequestId}`);
        const data = await response.json();
        setMaterialRequest(data.material_request);
      } catch (error) {
        console.error('Error fetching material request:', error);
      }
    };
    fetchMaterialRequest();
  }, [materialRequestId]);

  if (!materialRequest) {
    return <p>Material Request not found.</p>;
  }

  return (
    <div className="container">
      <div className="show-material-request">
        <h1>Material Request Details</h1>
        <div className="section">
          <h2>Request Information</h2>
          <table>
            <tbody>
              <tr>
                <th>Request ID</th>
                <td>{materialRequest.request_id}</td>
              </tr>
              <tr>
                <th>User</th>
                <td>{materialRequest.user}</td>
              </tr>
              <tr>
                <th>Total Price</th>
                <td>{materialRequest.total_price}</td>
              </tr>
              <tr>
                <th>Datetime</th>
                <td>{materialRequest.datetime}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <div className="section">
          <h2>Addresses and Items</h2>
          {materialRequest.addresses.map((address, index) => (
            <div key={index} className="address-section">
              <h3>{address.address}</h3>
              <p>Total Price: {address.total_price}</p>
              <table>
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>Count</th>
                    <th>Spec</th>
                    <th>Unit</th>
                    <th>Price per Unit</th>
                    <th>Total Price</th>
                  </tr>
                </thead>
                <tbody>
                  {address.items.map((item, itemIndex) => (
                    <tr key={itemIndex}>
                      <td>{item.name}</td>
                      <td>{item.count}</td>
                      <td>{item.spec}</td>
                      <td>{item.unit}</td>
                      <td>{item.price_per_unit}</td>
                      <td>{item.total_price}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ))}
        </div>
        <a href="/database" className="button">Back to Index</a>
        <a href={`/export_excel/${materialRequest.request_id}`} className="button">导出</a>
      </div>
    </div>
  );
};

export default ShowMaterialRequest;
